
package com.gregbugaj.nativequeryidl.converters;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Hold all the registered converters
 * @author devil
 *
 */
public class ConverterRegistry {
	private static   List<Converter<?>> converters;
	private static Map<Class<?>, Converter<?>> converterCache;

	//FIXME:Need to move this out of this static block
	static{
		converters=new ArrayList<Converter<?>>();
		converterCache=new HashMap<Class<?>, Converter<?>>();

		register(new BooleanConverter());
		//register(new ClobConverter());
		register(new DefaultConverter());
	}

	private  ConverterRegistry() {
	}



	/**
	 * Add new converter
	 * @param converter to add
	 */
	public static void register(Converter<?> converter) {
		converters.add(converter);		
	}

	/**
	 * Lookup existing converter if nothing found return default converter
	 * @param type
	 */
	@SuppressWarnings("unchecked")
	public static <T> Converter<T> lookup(Class<T> type) {
		Converter<?> cachedConverter=converterCache.get(type);
		if(cachedConverter!=null){
			return (Converter<T>) cachedConverter;
		}
		for(Converter<?> converter:converters){
			if(converter.canConvert(type)){
				converterCache.put(type, converter);
				return (Converter<T>) converter;
			}			
		}
		return null;
	}

}
